<?php

namespace App\Http\Controllers\Admin\Manager;

use Auth;
use Hash;
use Validator;
use App\Models\Admin\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProfileController extends Controller
{   
    public $module = 'profile_tag';

    public $parent_module = 'admin';

    public $breadcrumb_name = 'profile';

    public $page_name = '个人信息';

    public $page_describe = '查看个人信息';
    
    /**
     * @return \Illuminate\Http\Response
     */
    public function show()
    {
        $admin = Auth::guard('admin')->user();

        return view('manager.profile.show', ['admin' => $admin]);
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $this->validate($request, [
                'name' => 'required',
            ]);
            $admin = Admin::find($id);
            $admin->name = $request->get('name');
            $admin->save();
            return redirect()->back();
        } catch (Exception $e) {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()));
        }
    }

    public function reset(Request $request)
    {
        try {
            $v = Validator::make($request->all(), [
                'email' => 'required',
                'password_current' => 'required|min:6',
                'password' => 'required|confirmed|min:6',
            ]);

            $admin = Admin::where('email', $request->get('email'))->first();

            $v->after(function($v) use ($request, $admin) {
                if (!\Hash::check($request->get('password_current'), $admin->password)) {
                    $v->errors()->add('password_current', '原密码错误');
                }
            });

            if ($v->fails()) {
                return back()->withErrors($v);
            }

            if ($v->passes()) {
                $admin->password = Hash::make($request->get('password'));
                $admin->save();
                return redirect()->back()->withSuccess('修改密码成功');
            }
                
        } catch (Exception $e) {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()));
        }
    }
}
